<?php
!defined('M_COM') && exit('No Permission');
function rebuild_cache($except = ''){
	$excepts = $except ? explode(',',$except) : array();
	$cacarr = array(
	'channels','fchannels','mchannels','players','fcatalogs','currencys','grouptypes','cotypes','rprojects','permissions',
	'crprojects','mtconfigs','amconfigs','commus','sitemaps','mconfigs','localfiles','crprices','vcatalogs','badwords','wordlinks','dbsources','splangs',
	'menus','mmenus','uprojects','freeinfos','usualurls','dbfields','mcatalogs','faces','domains','mcnodes','aurls','cntpls','cnrels','abrels',
	'linknodes','watermarks','mctypes','catalogs','cnodes','gmodels','gmissions','splitbls','static_process','mspacepaths','frcatalogs','fragments',
	'cnconfigs','bannedips','pagecaches',
	);
	foreach($cacarr as $k){
		if(!in_array($k,$excepts)){
			if($k == 'catalogs') cn_dborder(0);
			updatecache($k);
		}
	}
	if(!in_array('fields',$excepts)){
		$vars = array_keys(reload_cache('channels'));
		$vars[] = 0;
		foreach($vars as $k) updatecache('fields',$k);
	}
	if(!in_array('mfields',$excepts)){
		$vars = array_keys(reload_cache('mchannels'));
		$vars[] = 0;
		foreach($vars as $k) updatecache('mfields',$k);
	}
	if(!in_array('ffields',$excepts)){
		$vars = array_keys(reload_cache('fchannels'));
		foreach($vars as $k) updatecache('ffields',$k);
	}
	if(!in_array('cufields',$excepts)){
		$vars = array_keys(reload_cache('commus'));
		foreach($vars as $k) updatecache('cufields',$k);
	}
	if(!in_array('abfields',$excepts)){
		$vars = array_keys(reload_cache('abrels'));
		foreach($vars as $k) updatecache('abfields',$k);
	}
	if(!in_array('cnfields',$excepts)){
		foreach(array(0,1) as $k) updatecache('cnfields',$k);
	}
	if(!in_array('usergroups',$excepts)){
		$vars = array_keys(reload_cache('grouptypes'));
		foreach($vars as $k) updatecache('usergroups',$k);
	}
	if(!in_array('coclasses',$excepts)){
		$vars = array_keys(reload_cache('cotypes'));
		foreach($vars as $k){
			cn_dborder($k);
			updatecache('coclasses',$k);
		}
	}
}
function updatecache($cname,$mode = ''){
	global $db,$tblprefix;
	$do = extend_cache('cachedos');
	switch($cname){
		case 'channels':
		case 'commus':
		case 'abrels':
		case 'aurls':
		case 'cnrels':
		case 'cotypes':
		case 'mctypes':
		case 'fragments':
		case 'fchannels':
		case 'currencys':
		case 'static_process':
		case 'cnconfigs':
		case 'mcatalogs':
		case 'mchannels':
		case 'dbsources':
		case 'players':
		case 'gmodels':
		case 'gmissions':
		case 'grouptypes':
		case 'rprojects':
		case 'watermarks':
		case 'uprojects':
		case 'permissions':
		case 'crprojects':
		case 'mtconfigs':
		case 'amconfigs':
		case 'sitemaps':
		case 'freeinfos':
		case 'vcatalogs':
		case 'usualurls':
			$$cname = cache_array($do[$cname]);
			cache2file($$cname,$cname);
			break;
		case 'fields':
		case 'mfields':
		case 'ffields':
		case 'cnfields':
		case 'cufields':
		case 'abfields':
			$arr = array('fields' => 'a','mfields' => 'm','ffields' => 'f','cnfields' => 'cn','cufields' => 'cu','abfields' => 'ab',);
			$do['fields']['where'] = "type='".$arr[$cname]."' AND tpid='$mode' AND available=1";
			$$cname = cache_array($do['fields']);
			cache2file($$cname,$cname.$mode,$cname);
			break;
		case 'fcatalogs':
			$$cname = cache_array($do[$cname]);
			$$cname = order_arr($$cname,0);
			cache2file($$cname,$cname);
			break;
		case 'frcatalogs':
			$$cname = cache_array($do[$cname]);
			foreach($frcatalogs as $k => $v) $frcatalogs[$k] = $v['title'];
			cache2file($$cname,$cname);
			break;
		case 'splitbls':
			$$cname = cache_array($do[$cname]);
			foreach($splitbls as $k => $v) $splitbls[$k]['chids'] = empty($v['chids']) ? array() : array_filter(explode(',',$v['chids']));
			cache2file($$cname,$cname);
			break;
		case 'mspacepaths':
			$mspacepaths = array();
			$na = cache_array($do[$cname]);
			foreach($na as $v) $mspacepaths[$v['mid']] = $v['mspacepath'];
			cache2file($$cname,$cname);
			break;
		case 'bannedips':
			global $timestamp;
			$bannedips = array();
			$do[$cname]['where'] = "enddate=0 || enddate>'$timestamp'";
			$na = cache_array($do[$cname]);
			foreach($na as $v){
				$str = '';
				for($i = 1;$i < 5;$i ++){
					$str .= ($str ? '\.' : '').($v["ip$i"] == -1 ? '\d+' : $v["ip$i"]);
				}
				$bannedips[] = $str;
			}
			cache2file($$cname,$cname);
			break;
		case 'catalogs':
			$$cname = cache_array($do[$cname]);
			$arr = array('trueorder','closed',);
 			$na = $sa = array();
			foreach($catalogs as $k => $v){
				$na[$k] = array('s' => $v['dirname']);
				$topid = cn_upid($k,$catalogs);
				if($topid != $k) $na[$k]['p'] = $catalogs[$topid]['dirname'];
				if($v['customurl']) $na[$k]['u'] = $v['customurl'];
				if($pids = cn_pids($k,$catalogs)) foreach($pids as $x) $sa[$x][] = $k;
				arr_tag2atm($catalogs[$k],'ca');
				foreach(array('apmid','rpmid','crpmid','dpmid','allowsale','allowfsale','taxcp','awardcp','ftaxcp',) as $z)if(empty($v[$z]))unset($catalogs[$k][$z]);
				foreach($arr as $z)unset($catalogs[$k][$z]);
			}
			foreach($sa as $x => $y) $sa[$x] = implode(',',$y);
			cache2file($sa,"cnsonids0");
			cache2file($na,"cndirnames0");
			cache2file($$cname,$cname);
			break;
		case 'usergroups':
			$do[$cname]['where'] = "gtid='$mode'";
			$$cname = cache_array($do[$cname]);
			cache2file($$cname,$cname.$mode);
			break;
		case 'coclasses':
			$do[$cname]['where'] = "coid='$mode' AND closed=0";
			$$cname = cache_array($do[$cname]);
			$na = $sa = array();
			foreach($coclasses as $k => $v){
				$na[$k] = array('s' => $v['dirname']);
				$topid = cn_upid($k,$coclasses);
				if($topid != $k) $na[$k]['p'] = $coclasses[$topid]['dirname'];
				if($pids = cn_pids($k,$coclasses)) foreach($pids as $x) $sa[$x][] = $k;
				arr_tag2atm($coclasses[$k],'cc');
				$arr = array('trueorder','closed',);foreach(array('conditions','apmid','rpmid','crpmid','dpmid','allowsale','allowfsale','taxcp','awardcp','ftaxcp',) as $z) empty($v[$z]) && $arr[] = $z; 
				foreach($arr as $z) unset($coclasses[$k][$z]);
			}
			foreach($sa as $x => $y) $sa[$x] = implode(',',$y);
			cache2file($sa,"cnsonids$mode");
			cache2file($na,"cndirnames$mode");
			cache2file($coclasses,$cname.$mode,$cname);
			break;
		case 'splangs':
			$$cname = cache_array($do[$cname]);
			foreach($splangs as $k => $v) $splangs[$k] = $v['content'];
			cache2file($$cname,$cname);
			break;
		case 'cnodes':
			$cnodes = array();
			$query = $db->query("SELECT ename,alias,appurl,tid FROM {$tblprefix}cnodes WHERE closed=0");
			while($row = $db->fetch_array($query)){
				$cnstr = $row['ename'];unset($row['ename']);
				foreach(array('alias','appurl','tid',) as $k) if(!$row[$k]) unset($row[$k]);
				$cnodes[$cnstr] = $row;
			}
			cache2file($cnodes,'cnodes');
			unset($cnodes,$row);
			break;
		case 'mcnodes':
			$mcnodes = array();
			$query = $db->query("SELECT ename,alias,appurl,tid FROM {$tblprefix}mcnodes WHERE closed=0");
			while($row = $db->fetch_array($query)){
				$cnstr = $row['ename'];unset($row['ename']);
				foreach(array('alias','appurl','tid',) as $k) if(!$row[$k]) unset($row[$k]);
				$mcnodes[$cnstr] = $row;
			}
			cache2file($mcnodes,'mcnodes','');
			unset($mcnodes,$row);
			break;
		case 'mconfigs':
			global $mconfigs,$mcharset,$cms_version,$homedefault,$cms_abs,$cmsurl;
			if(empty($$cname)){
				$$cname = cache_array($do[$cname]);
				$fromdb = true;
			}else $fromdb = false;
			$btags = array();
			foreach($mconfigs as $k => $v){
				if($fromdb){
					$mconfigs[$k] = $v = $v['value'];
					in_array($k,array('cn_urls','cn_periods',)) && $mconfigs[$k] = explode(',',$v);
				}
				
				in_array($k,array('hostname','hosturl','cmsname','cmsurl','cmslogo','cmstitle','cmskeyword','cmsdescription','cms_icpno','bazscert','copyright',)) && $btags[$k] = $v;
			}
			$cmsurl = $mconfigs['cmsurl'];
			$cms_abs = $mconfigs['cms_abs'] = $btags['cms_abs'] = strpos($mconfigs['cmsurl'],$mconfigs['hosturl']) === FALSE ? ($mconfigs['hosturl'].$mconfigs['cmsurl']) : $mconfigs['cmsurl'];
			$mconfigs['cms_rel'] = $btags['cms_rel'] = strpos($cmsurl,$mconfigs['hosturl']) === FALSE ? $cmsurl : str_replace($mconfigs['hosturl'],'',$cmsurl);
			$mconfigs['cms_top'] = $btags['cms_top'] = top_domain($mconfigs['hosturl']);
			foreach(array('member','mspace','mobile',) as $k) $mconfigs[$k.'url'] = $btags[$k.'url'] = function_exists('view_url') ? view_url($mconfigs[$k.'dir'].'/') : $cms_abs.$mconfigs[$k.'dir'].'/';
			$btags['mcharset'] = $mcharset;$btags['version'] = $cms_version;
			$btags['tplurl'] = $cms_abs.'template/'.$mconfigs['templatedir'].'/';
			foreach(array('btags',$cname) as $k) cache2file($$k,$k);
			break;
		case 'localfiles':
			$inits = cache_array($do[$cname]);
			foreach($inits as $v) $localfiles[$v['ftype']][$v['extname']] = $v;
			cache2file($$cname,$cname);
			break;
		case 'crprices':
			$$cname = cache_array($do[$cname]);
			$vcps = array('tax' => array(),'sale' => array(),'award' => array(),'ftax' => array(),'fsale' => array(),);
			foreach($crprices as $k => $v){
				foreach(array('tax','sale','award','ftax','fsale') as $var){
					$v[$var] && $vcps[$var][$v['ename']] = $v['cname'];
				}
			}
			cache2file($vcps,'vcps');
			cache2file($$cname,$cname);
			break;
		case 'badwords':
			$badwords = array();
			$query = $db->query("SELECT * FROM {$tblprefix}badwords ORDER BY bwid");
			while($badword = $db->fetch_array($query)){
				$badwords['wreplace'][] = $badword['wreplace'];
				$badword['wsearch'] = preg_replace("/\\\{(\d+)\\\}/", ".{0,\\1}", preg_quote($badword['wsearch'],'/'));
				$badwords['wsearch'][] = '/'.$badword['wsearch'].'/i';
			}
			cache2file($$cname,$cname);
			break;
		case 'wordlinks':
			$wordlinks = $uwordlinks = array();
			$query = $db->query("SELECT * FROM {$tblprefix}wordlinks WHERE available=1 ORDER BY pcs DESC");
			while($row = $db->fetch_array($query)){
				$wordlinks['swords'][] = '/'.preg_quote($row['sword'],'/').'/i';
				$wordlinks['rwords'][] = '<a href="'.view_url($row['url']).'" target="_blank">'.$row['sword'].'</a>';
				$uwordlinks['swords'][] = $row['sword'];
				$uwordlinks['rwords'][] = view_url($row['url']);
			}
			cache2file($$cname,$cname);
			cache2file($uwordlinks,'uwordlinks');
			break;
		case 'domains':
			$domains = array('from' => array(),'to' => array(),);
			$query = $db->query("SELECT domain,folder,isreg FROM {$tblprefix}domains ORDER BY vieworder,id");
			while($row = $db->fetch_array($query)){
				$domains['from'][] = $row['isreg'] ? $row['folder'] : u_regcode($row['folder']);
				$domains['to'][] = $row['domain'];
			}
			cache2file($$cname,$cname);
			break;
		case 'faces':
			$faceicons = array('from' => array(),'to' => array(),);
			$jsstr = 'var FACEICONS = [';
			$query = $db->query("SELECT * FROM {$tblprefix}facetypes WHERE available=1 ORDER BY vieworder,ftid");
			while($row = $db->fetch_array($query)){
				$jsstr .= '[\''.$row['cname'].'\',[';
				$query1 = $db->query("SELECT * FROM {$tblprefix}faces WHERE ftid='$row[ftid]' AND available=1 ORDER BY vieworder,id");
				while($row1 = $db->fetch_array($query1)){
					$faceicons['from'][] = $row1['ename'];
					$faceicons['to'][] = 'images/face/'.$row['facedir'].'/'.$row1['url'];
					$jsstr .= '[\''.$row1['ename'].'\',\'images/face/'.$row['facedir'].'/'.$row1['url'].'\'],';
				}
				$jsstr .= ']],';
			}
			$jsstr .= '];';
			str2file($jsstr,M_ROOT.'./dynamic/cache/faceicons.js');
			cache2file($faceicons,'faceicons');
			break;
		case 'dbfields':
			$dbfields = array();
			$query = $db->query("SELECT * FROM {$tblprefix}dbfields ORDER BY dfid");
			while($row = $db->fetch_array($query)){
				$dbfields[$row['ddtable'].'_'.$row['ddfield']] = $row['ddcomment'];
			}
			cache2file($$cname,$cname);
			break;
		case 'menus':
			$mnmenus = array();
			$query1 = $db->query("SELECT * FROM {$tblprefix}mtypes ORDER BY vieworder");
			while($row1 = $db->fetch_array($query1)){
				$mnmenus[$row1['mtid']] = array(
					'title' => $row1['title'],
					'childs'=> array()
				);
				$query2 = $db->query("SELECT * FROM {$tblprefix}menus WHERE mtid='$row1[mtid]' AND available=1 AND isbk=0 ORDER BY vieworder");
				while($row2 = $db->fetch_array($query2)){
					$mnmenus[$row1['mtid']]['childs'][$row2['mnid']] = array(
						'title' => $row2['title'],
						'url'=> $row2['url']
					);
				}
				if(empty($mnmenus[$row1['mtid']]['childs']))unset($mnmenus[$row1['mtid']]);
			}
			cache2file($mnmenus,'mnmenus');
			break;
		case 'mmenus':
			$mmnmenus = array();
			$query = $db->query("SELECT * FROM {$tblprefix}mmtypes ORDER BY vieworder,mtid");
			while($row0 = $db->fetch_array($query)){
				$mmnmenus[$row0['mtid']]['title'] = $row0['title'];
				$mmnmenus[$row0['mtid']]['menuimage'] = $row0['menuimage'];	
 				$mmnmenus[$row0['mtid']]['submenu'] = array();
				$query1 = $db->query("SELECT * FROM {$tblprefix}mmenus WHERE mtid='$row0[mtid]' AND available=1 AND isbk='0' ORDER BY vieworder,mnid");
				while($row1 = $db->fetch_array($query1)){
					$mmnmenus[$row0['mtid']]['submenu'][$row1['mnid']] = array(
					'title' => $row1['title'],
					'url' => $row1['url'],
					'pmid' => $row1['pmid'],
					'newwin' => $row1['newwin'],
					'onclick' => $row1['onclick'],
					);
				}
			}
			cache2file($mmnmenus,'mmnmenus');
			break;
		case 'cntpls':
			$$cname = cache_array($do['cntpls']);
			cache2file($$cname,'cntpls');
			$$cname = cache_array($do['mcntpls']);
			cache2file($$cname,'mcntpls');
			break;
		case 'linknodes':
			$query = $db->query("SELECT * FROM {$tblprefix}variables WHERE type='$cname' ORDER BY variable ASC");
			${$cname} = array();
			while($row = $db->fetch_array($query)){
				${$cname}[$row['variable']] = is_array($row['content'] = @unserialize($row['content'])) ? $row['content'] : array();
			}
			cache2file($$cname,$cname);
			break;
		case 'pagecaches':
			$$cname = cache_array($do[$cname]);
			$na = array();
			foreach($pagecaches as $k => $v){
				$typeid = $v['typeid'];$pcid = $v['pcid'];
				foreach(array('pcid','cname','typeid','cfgs','vieworder','available',) as $key) unset($v[$key]);
				$na[$typeid][$pcid] = $v;
			}
			for($i=1;$i<10;$i++) cache2file(empty($na[$i]) ? array() : $na[$i],"pagecaches$i");
			break;
	}
}
function cache_array($do = array()){//$do = array(tbl,key,fieldstr,where,orderby,unserialize,explode,unset,varexport,merge,)
	global $db,$tblprefix;
	$rets = array();
	if(empty($do['tbl']) || empty($do['key'])) return $rets;
	empty($do['fieldstr']) && $do['fieldstr'] = '*';
	$sqlstr = "SELECT $do[fieldstr] FROM {$tblprefix}$do[tbl]".(empty($do['where']) ? '' : " WHERE $do[where]").(empty($do['orderby']) ? '' : " ORDER BY $do[orderby]");
	$query = $db->query($sqlstr);
	while($r = $db->fetch_array($query)){
		if(!empty($do['unserialize']) && is_array($x = array_filter(explode(',',$do['unserialize'])))){
			foreach($x as $v) if(empty($r[$v]) || !is_array($r[$v] = @unserialize($r[$v]))) $r[$v] = array();
		}
		if(!empty($do['explode']) && is_array($x = array_filter(explode(',',$do['explode'])))){
			foreach($x as $v) $r[$v] = $r[$v] == '' ? array() : explode(',',$r[$v]);
		}
		if(!empty($do['unset']) && is_array($x = array_filter(explode(',',$do['unset'])))){
			foreach($x as $v) unset($r[$v]);
		}
		if(!empty($do['varexport']) && is_array($x = array_filter(explode(',',$do['varexport'])))){
			foreach($x as $v) $r[$v] = varexp2arr($r[$v]);
		}
		if(!empty($do['merge']) && is_array($x = array_filter(explode(',',$do['merge'])))){
			foreach($x as $v){
				if(isset($r[$v]) && is_array($r[$v])){
					$r += $r[$v];
					unset($r[$v]);
				}
			}
		}
		$rets[$r[$do['key']]] = $r;
	}
	return $rets;
}
function mfetch_fields($tbls = ''){
	global $db,$tblprefix;
	$rets = array();
	if($tbls && is_array($x = explode(',',$tbls))){
		foreach($x as $v){
			$query = $db->query("SELECT * FROM {$tblprefix}$v");
			while($field = $db->fetch_fields($query)) $rets[] = $field->name;
		}
		$rets = array_unique($rets);
	}
	return $rets;
}
function cn_dborder($coid=0){
	global $db,$tblprefix;
	$do = extend_cache('cachedos');
	if($coid){
		$do['orderccid']['where'] = "coid='$coid'";
		$na = cache_array($do['orderccid']);
	}else $na = cache_array($do['ordercaid']);
	$na = order_arr($na,0);
	$i = 0;
	foreach($na as $k => $v){
		$db->query($coid ? "UPDATE {$tblprefix}coclass SET trueorder=$i WHERE ccid=$k" : "UPDATE {$tblprefix}catalogs SET trueorder=$i WHERE caid=$k",'SILENT');
		$i ++;
	}
	unset($na);
}
function cn_pids($id,&$sarr){
	$ret = array();
	while($sarr[$id]['pid']) $ret[] = $id = $sarr[$id]['pid'];
	return $ret;
}
function top_domain($v){
	global $sysparams;
	$sysparams || $sysparams = sys_cache('sysparams');
	if(strpos($v,':') !== FALSE){
		$na = parse_url($v);
		if(!empty($na['host'])) $v = $na['host'];
	}
	if(!empty($sysparams['suffix']) && preg_match("/(^|\.)(([^\.])+\.($sysparams[suffix])+$)/",$v,$matches) && !empty($matches[2])){
		$v = $matches[2];
	}else $v = '';
	return $v;
}
?>
